package com.user.infrastructure.listener;

import com.common.InterceptorChain.BusinessInterceptorChain;
import com.common.InterceptorChain.BusinessInterceptorChainFactory;
import com.event.DomainEvent;
import com.event.DomainEventListener;
import com.user.domain.entity.User;
import com.user.domain.entity.UserSignIn;
import com.user.domain.repository.UserSignInRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.HashMap;

import static com.user.domain.event.UserEventEnum.*;

/**
 * @author 大忽悠
 * @create 2022/9/15 23:25
 */
@Component
@Slf4j
public class UserLoginListener extends DomainEventListener {
    private final UserSignInRepository userSignInRepository;
    /**
     * 业务逻辑拦截器链
     */
    private static final BusinessInterceptorChain businessInterceptorChain= BusinessInterceptorChainFactory.newBusinessInterceptorChain();
    private static final String businessContextKey="domainEvent";

    public UserLoginListener(UserSignInRepository userSignInRepository) {
        this.userSignInRepository = userSignInRepository;
        init();
    }

    /**
     * 初始化相关拦截器
     */
    private void init() {
        businessInterceptorChain.addInterceptor(businessContext -> {
            DomainEvent domainEvent = (DomainEvent) businessContext.getAttr(businessContextKey);
            if(domainEvent.getEventType().equals(USER_LOGIN_EVENT.getEventType())){
                log.info("用户登录事件: {}",domainEvent);
                //用户签到
                UserSignIn.userSignIn(userSignInRepository, (Integer) domainEvent.getSource());
            }
            return true;
        });
        businessInterceptorChain.addInterceptor(businessContext -> {
            DomainEvent domainEvent = (DomainEvent) businessContext.getAttr(businessContextKey);
            if(domainEvent.getEventType().equals(USER_INSERT_EVENT.getEventType())){
                log.info("用户注册事件: {}",domainEvent);
                //用户签到
                UserSignIn.userSignIn(userSignInRepository, ((User) domainEvent.getSource()).getId());
            }
            return true;
        });
    }

    /**
     * 是否支持当前领域事件
     *
     * @param domainEvent
     */
    @Override
    protected boolean supportDomainEvent(DomainEvent domainEvent) {
        return domainEvent.getDomain().equals(USER_DOMAIN);
    }

    /**
     * 处理接收到的领域事件
     *
     * @param domainEvent
     */
    @Override
    protected void doHandleDomainEvent(DomainEvent domainEvent) {
        HashMap<Object, Object> map = new HashMap<>();
        map.put(businessContextKey,domainEvent);
        businessInterceptorChain.interceptor(BusinessInterceptorChainFactory.newBusinessContext(map));
    }
}
